/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pub;

import Utils.Static;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.CategoryModel;
import models.ProductModel;

/**
 *
 * @author user
 */
public class products extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            HttpSession session = request.getSession(true);
            if (session.getAttribute(Static.categories) == null) {
                response.sendRedirect("load");
                return;
            }
            ArrayList<String> script = new ArrayList<String>();
            script.add("<script type=\"text/javascript\">!window.jQuery && document.write('<script src=\"jscripts/fancybox/jquery-1.4.3.min.js\"><\\/script>');</script>");
            script.add("<script type=\"text/javascript\" src=\"jscripts/fancybox/jquery.mousewheel-3.0.4.pack.js\"></script>");
            script.add("<script type=\"text/javascript\" src=\"jscripts/fancybox/jquery.fancybox-1.3.4.pack.js\"></script>");
            script.add("<link rel=\"stylesheet\" type=\"text/css\" href=\"jscripts/fancybox/jquery.fancybox-1.3.4.css\" media=\"screen\" />");
            script.add("<script type=\"text/javascript\" src=\"jscripts/products.js\"></script>");
            session.setAttribute(Static.java_script, script);

            String action = request.getParameter(Static.action);
            if (action == null) {
                Index(request, response);
            } else if (action.compareTo("details") == 0) {
                Details(request, response);
            } else {
                Index(request, response);
            }

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void Index(HttpServletRequest request, HttpServletResponse response) {
        try {

            HttpSession session = request.getSession(true);
            String sortFields[][] = {{"Name", "Nume"}, {"Quantity", "Cantitate"}, {"Price", "Pret"}};
            String sort = sortFields[0][0];
            int pageSize = 9;
            int currPage = 1;
            int firstPage = 1;
            String sortDir = "asc";
            int categoryID = - 1;

            if (request.getParameter(Static.sort) != null) {
                sort = request.getParameter(Static.sort);
            }

            if (request.getParameter(Static.sortDir) != null) {
                sortDir = request.getParameter(Static.sortDir).compareTo("desc") == 0 ? "desc" : "asc";
            }

            if (request.getParameter(Static.currPage) != null) {
                currPage = Integer.parseInt(request.getParameter(Static.currPage));
            }

            if (request.getParameter(Static.firstPage) != null) {
                firstPage = Integer.parseInt(request.getParameter(Static.firstPage));
            }

            if (request.getParameter(Static.catID) != null) {
                categoryID = Integer.parseInt(request.getParameter(Static.catID));
            }


//calculez numarul de pagini
            ProductModel model = new ProductModel();
            int recordsCount = model.GetProducts_Count(categoryID);
            int pageCount = (int) (recordsCount / pageSize);

//extrag pagina currPage
            int offset = (currPage - 1) * pageSize;
            ArrayList products = model.GetProducts(offset, pageSize, sort, sortDir, categoryID);

//adaug variabilele in sesiune in sesiune

            session.setAttribute(Static.currPage, currPage);
            session.setAttribute(Static.firstPage, firstPage);
            session.setAttribute(Static.pageCount, pageCount);
            session.setAttribute(Static.sort, sort);
            session.setAttribute(Static.sortDir, sortDir);
            session.setAttribute(Static.sortFields, sortFields);
            session.setAttribute(Static.products, products);

            getServletContext().getRequestDispatcher("/pub/products/index.jsp").forward(request, response);

        } catch (Exception ex) {
        }
    }


    public void Details(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);
            int productID = Integer.parseInt(request.getParameter("prodID"));

            ProductModel productModel = new ProductModel();
            HashMap product = productModel.GetProduct(productID);

            CategoryModel categoryModel = new CategoryModel();
            Integer categoryID = Integer.parseInt(product.get("CategoryID").toString());
            HashMap subCategory = (HashMap) categoryModel.GetCategory((int) categoryID);
            Integer subCategoryID = Integer.parseInt(subCategory.get("CategoryMasterID").toString());
            HashMap category = (HashMap) categoryModel.GetCategory(subCategoryID);

            session.setAttribute(Static.product, product);
            session.setAttribute(Static.category, category);
            session.setAttribute(Static.subCategory, subCategory);

            getServletContext().getRequestDispatcher("/pub/products/details.jsp").forward(request, response);
        } catch (Exception ex) {
            String error = ex.getMessage();
        }
    }
}
